package WEB.servlet.actions;

import db.dao.IntakeDao;
import db.dto.IntakeDto;
import db.exceptions.IntakeDaoException;
import db.factory.IntakeDaoFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * User: Vanil
 * Date: 20.12.2010
 * Time: 17:48:32
 */
public class AddIntake implements Action {

    public String perform(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        int doctorId = new Integer(request.getParameter("doctor"));
        String comment = request.getParameter("comment");
        int patientId = new Integer(request.getParameter("patient"));
        int year = new Integer(request.getParameter("year"));
        int month = new Integer(request.getParameter("month"));
        int day = new Integer(request.getParameter("day"));
        int hour = new Integer(request.getParameter("hour"));
        int minute = new Integer(request.getParameter("minute"));
        Calendar cal= new GregorianCalendar();
        cal.set(year,month,day,hour,minute);
        IntakeDao intakeDao = IntakeDaoFactory.create();
        IntakeDto intakeDto = new IntakeDto();
        intakeDto.setIdDoctor(doctorId);
        intakeDto.setComment(comment);
        intakeDto.setIdPatient(patientId);
        intakeDto.setDateofintake(cal.getTimeInMillis());
        intakeDto.setPriority(0);

        try {
        String idIntakeStr = request.getParameter("idIntake");
            if(idIntakeStr!=null)
            {
                int idIntake = new Integer(idIntakeStr);
                intakeDto.setIdIntake(idIntake);
                intakeDao.update(idIntake,intakeDto);
            }
            else
                intakeDao.insert(intakeDto);

        } catch (IntakeDaoException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            request.getSession().setAttribute("errorMessage","invalid data.");
        return "/error.jsp";
        }
        return "/show.do?id="+patientId;

    }
}
